import Footer from '@/components/Footer';
import { login } from '@/services/ant-design-pro/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import {Alert, Divider, message, Tabs} from 'antd';
import React, { useState } from 'react';
import { history, Link, useModel } from 'umi';
import styles from './index.less';

//导入自定义常量
import { MY_CSDN_LINK, SYSTEM_LOGO } from '@/constants'; //logo


const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  /**
   * 点击登录后的处理
   * @param values
   */
  const handleSubmit = async (values: API.LoginParams) => {
    // 登录  后端响应用户信息
    const res = await login({
      ...values,
      type,
    });
    try {
      if (res.data) {   //返回了该用户信息代表登录成功
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as {
          redirect: string;
        };
        history.push(redirect || '/');
        return;
      }else{
        throw new Error(res.description);
      }
    } catch (error) {
      // setUserLoginState({        status: 'error',       type: 'account'     });
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error( res.description ?? defaultLoginFailureMessage);
    }
  };

  /**
   * 需要在后面加上 || {} 允许其内的属性值为空
   * 否则当登录失败时,res.data为空，因此 setUserLoginState(res.data) 会使得 userLoginState 为null
   * 导致结构表达式在取值时报错：TypeError: Cannot read properties of null (reading 'status')
   */
  const { status, type: loginType } = userLoginState ?? {};

  /**
   * 页面内容及表单参数校验
   */
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src={SYSTEM_LOGO} />}
          title="用户中心"
          subTitle={<a href={MY_CSDN_LINK} target="_blank" rel="noreferrer">为个人项目提供可视化的用户数据源 — 避免重复建库建表</a>}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="account" tab={<span style={{ fontSize: '14px' }}>登录</span>} />
          </Tabs>

          {status === 'error' && loginType === 'account' && (
            <LoginMessage content={'错误的账号和密码'}/>
          )}

          {type === 'account' && (
            <>
              <ProFormText  //表单中的字段
                name="userAccount"   //字段名称。注意：需要与封装请求参数的LoginParams中的属性名一致，否则识别不到无法映射
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                  //自定义规则，前端校验密码不能小于8位
                  {
                    min: 8,
                    //min必须结合type一起使用，当type为num时表示数字最小值，为string时表示字符串的最小长度
                    type: 'string',
                    message: '小于8位！',
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <Divider type={"vertical"}/>
            <Link to="/user/register">新用户先注册趴</Link>
            <Divider type={"vertical"}/>
            <a
              style={{
                float: 'right',
              }}
              href={MY_CSDN_LINK}
              target="_blank" rel="noreferrer"
            >
              忘记密码?联系我
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
